import styles from './index.module.scss'
import { Table, Space, Card, Breadcrumb, Form, Button, Radio, Select, DatePicker, Tag, Image, Modal } from 'antd'
import { EditOutlined, DeleteOutlined } from "@ant-design/icons";
import { Link } from 'react-router-dom'
import { useChannels } from '@/utils/customHooks';
import { useEffect, useRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { delArticle, getArticles } from '@/store/actions/article';
import defaultImg from "@/assets/error.gif";
import { useHistory } from 'react-router-dom';

const statusLabel = [
    { text: "草稿", color: "default" },
    { text: "待审核", color: "blue" },
    { text: "审核通过", color: "green" },
    { text: "审核拒绝", color: "red" },
]


const Article = () => {
    const history = useHistory()
    const dispatch = useDispatch()
    const paramsRef = useRef({
        page: 1,
        per_page: 20,
        channel_id: undefined,
        status: undefined,
        begin_pubdate: undefined,
        end_pubdate: undefined,
    })

    const columns = [
        {
            title: "封面",
            dataIndex: "cover",
            key: "cover",
            render: (cover) => {
                let imgUrl = defaultImg
                if (cover?.images?.length) {
                    imgUrl = cover.images[0]
                }
                return <Image src={imgUrl} style={{ objectFit: "cover" }} width={200} height={120}></Image>
            }
        },
        {
            title: "标题",
            dataIndex: "title",
            key: "title",
        },
        {
            title: "状态",
            dataIndex: "status",
            key: "status",
            render: (status) => {
                return <Tag color={statusLabel[status].color}>{statusLabel[status].text}</Tag>;
            },
        },
        {
            title: "发布时间",
            dataIndex: "pubdate",
            key: "pubdate",
        },
        {
            title: "阅读数",
            dataIndex: "read_count",
            key: "read_count",
        },
        {
            title: "评论数",
            dataIndex: "comment_count",
            key: "comment_count",
        },
        {
            title: "点赞数",
            dataIndex: "like_count",
            key: "like_count",
        },
        {
            title: "操作",
            key: "action",
            render: (_, row) => (
                <Space size="middle">
                    <Button onClick={() => history.push((`/home/publish/${row.id}`))} type="link" icon={<EditOutlined />} />
                    <Button onClick={() => {
                        Modal.confirm({
                            title: "确定删除此文章吗？",
                            onOk: async () => {
                                // 调用删除接口
                                await dispatch(delArticle(row.id)) // 调用删除action
                                // 重新加载数据
                                dispatch(getArticles(paramsRef.current))
                            }
                        })
                    }} danger type="link" icon={<DeleteOutlined />} />
                </Space>
            ),
        },
    ]

    const channels = useChannels()
    const { results, page, per_page, total_count } = useSelector((state) => state.article)
    // 组件第一次渲染 dispatch 分发 action
    useEffect(() => {
        dispatch(getArticles(paramsRef.current))
    }, [dispatch])
    // 改变筛选条件查询
    const onFinish = (values) => {
        paramsRef.current.status = values.status
        paramsRef.current.channel_id = values.channel_id
        if (values.dateArr) {
            paramsRef.current.begin_pubdate = values.dateArr[0].format(
                "YYYY-MM-DD HH:mm:ss"
            )
            paramsRef.current.end_pubdate = values.dateArr[1].format(
                "YYYY-MM-DD HH:mm:ss"
            )
        } else {
            paramsRef.current.begin_pubdate = undefined
            paramsRef.current.end_pubdate = undefined
        }
        paramsRef.current.page = 1
        dispatch(getArticles(paramsRef.current))
    }
    // 改变分页和size重新查询
    const onPageChange = (page, pageSize) => {
        paramsRef.current.page = page
        paramsRef.current.per_page = pageSize
        dispatch(getArticles(paramsRef.current));
    }
    return <div className={styles.root}>
        <Card
            title={
                // 面包屑
                <Breadcrumb>
                    <Breadcrumb.Item>
                        <Link to="/home">首页</Link>
                    </Breadcrumb.Item>
                    <Breadcrumb.Item>内容管理</Breadcrumb.Item>
                </Breadcrumb>
            }
        >
            {/* 表单 */}
            <Form onFinish={onFinish}>
                <Form.Item name="status" label="状态：">
                    <Radio.Group>
                        <Radio value={undefined}>全部</Radio>
                        <Radio value={0}>草稿</Radio>
                        <Radio value={1}>待审核</Radio>
                        <Radio value={2}>审核通过</Radio>
                        <Radio value={3}>审核失败</Radio>
                    </Radio.Group>
                </Form.Item>
                <Form.Item name="channel_id" label="频道：">
                    <Select style={{ width: 288 }}>
                        {
                            channels.map(item => (
                                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item name="dateArr" label="日期：">
                    <DatePicker.RangePicker />
                </Form.Item>
                <Form.Item>
                    <Button type="primary" htmlType="submit">筛选</Button>
                </Form.Item>
            </Form>
        </Card>
        <Card
            title={`根据筛选条件共查询到 ${total_count} 条结果`}
            style={{ marginTop: 24 }}
        >
            <Table rowKey="id" columns={columns} dataSource={results} pagination={{
                current: page,
                pageSize: per_page,
                total: total_count,
                onChange: onPageChange
            }}></Table>
        </Card>
    </div>
}

export default Article
